package com.booktrade.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.booktrade.entity.Messages;
import com.booktrade.entity.Notifications;
import com.booktrade.mapper.MessagesMapper;
import com.booktrade.service.IMessagesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.apache.logging.log4j.message.Message;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 私信表，存储用户之间的消息 服务实现类
 * </p>
 */
@Service
@RequiredArgsConstructor
public class MessagesServiceImpl extends ServiceImpl<MessagesMapper, Messages> implements IMessagesService {
    private final MessagesMapper messageMapper;

    /**
     * 发送消息
     */
    public void sendMessage(Integer senderId, Integer receiverId, String content) {
        Messages message = new Messages();
        message.setSenderId(senderId);
        message.setReceiverId(receiverId);
        message.setContent(content);
        message.setIsRead(false);
        messageMapper.insert(message);
    }

    /**
     * 获取与某个用户的聊天记录
     */
    public List<Messages> getMessagesWithContact(Integer userId, Integer contactId) {
        LambdaQueryWrapper<Messages> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.and(wrapper ->
                        wrapper.eq(Messages::getSenderId, userId)
                                .eq(Messages::getReceiverId, contactId)
                                .or()
                                .eq(Messages::getSenderId, contactId)
                                .eq(Messages::getReceiverId, userId))
                .orderByAsc(Messages::getCreatedAt);
        return messageMapper.selectList(queryWrapper);
    }

    /**
     * 查询用户私聊过的所有其他用户ID
     */
    public List<Integer> getAllContacts(Integer userId) {
        // 使用 MyBatis-Plus 的 LambdaQueryWrapper 进行查询
        List<Integer> sentContactIds = messageMapper.selectDistinctContactIds(userId, true);
        List<Integer> receivedContactIds = messageMapper.selectDistinctContactIds(userId, false);

        // 合并发送和接收的联系人ID并去重
        Set<Integer> contactIds = new HashSet<>(sentContactIds);
        contactIds.addAll(receivedContactIds);

        return new ArrayList<>(contactIds);
    }
}
